const fs = require('fs');
const eachLimit = require('async/eachLimit');
const path = require('path');
const squel = require('squel');
const mySqlutil = require('../utils/mysql_util');
const logUtil = require('../utils/log_util');
// const mongod=require('../utils/mongod_util');
const { gridFs } = require('../utils/mongod_util');
const projectJsonCrtl = require('./project_json_ctrl');
const streamBuffers = require('stream-buffers');

const gridFSBuckets=require('../mongod/gridFSBuckets');


/**
 * 保存方案或户型界面截图
 * @param strImage
 * @param fileName
 */
const saveStrImage = (strImage, fileName) => new Promise((res, rej) => {
  if (strImage) {
    fileName = fileName || `${uuid4.toString()}.jpg`;
    const image = strImage.replace(/^data:image\/\w+;base64,/, '');
    const dataBuffer = new Buffer(image, 'base64');
    gridFs().then((result) => {
      result.exist({
        filename: fileName,
        root: 'project_image'
      },(err,found)=>{
if(err) rej(err);
if(found){

}

      });
      result.remove({
        filename: fileName,
        root: 'project_image'
      }, (err) => {
        if (err) logUtil.error(err);
        const writeStream = result.createWriteStream({
          filename: fileName,
          root: 'project_image'
        });
        const readStreamBuffer = new streamBuffers.ReadableStreamBuffer();
        readStreamBuffer.put(dataBuffer);
        readStreamBuffer.pipe(writeStream);
        writeStream.on('close', () => {
          // do something with `file`
          res();
        });

        writeStream.on('error', (err) => {
          // do something with `file`
          rej(err);
        });
        readStreamBuffer.stop();
      });
    });
  } else {
    res();
  }
});
/**
 * mongodb gridFs图片复制
 * @param oldName
 * @param newName
 */
const copyAndSaveImage = (oldName, newName) => new Promise((res, rej) => {
  if (!oldName || oldName.trim().length === 0) {
    res();
  } else {
    gridFs().then((result) => {
      const readStream = result.createReadStream({
        filename: oldName,
        root: 'project_image'
      });
      const writeStream = result.createWriteStream({
        filename: newName,
        root: 'project_image'
      });
      writeStream.on('close', () => {
        // do something with `file`
        res();
      });

      writeStream.on('error', (err) => {
        // do something with `file`
        rej(err);
      });
      readStream.on('error', (err) => {
        // do something with `file`
        rej(err);
      });
      readStream.pipe(writeStream);
    });
  }
});

// /**
//  * 分析用户所建方案，提取并保存方案所用模型信息
//  * @param strData
//  */
// const saveContentByProject = (strData, designId) => new Promise((res, rej) => {
//   logUtil.info('提前方案中模型信息，并保存到业务表格！');
//   const projectData = JSON.parse(strData);
//   if (projectData.data) {
//     // 获取方案部件列表
//     const partList = projectData.data;
//     // 删除当前方案上次保存的模型信息
//     mySqlutil.execute(projectContentDao.delete(designId)).then(() => {
//       // 分解方案，保存方案中所用模型信息
//       eachLimit(partList, 10, (part, callback) => {
//         if (part.Class && part.Class.toString() === 'hsw.model.Content') {
//           const param = {};
//           param.designId = designId;
//           if (part.x) {
//             param.x = part.x;
//           }
//           if (part.y) {
//             param.y = part.y;
//           }
//           if (part.z) {
//             param.z = part.z;
//           }
//           if (part.XLength) {
//             param.x_length = part.XLength;
//           }
//           if (part.YLength) {
//             param.y_length = part.YLength;
//           }
//           if (part.ZLength) {
//             param.z_length = part.ZLength;
//           }
//           if (part.rotation) {
//             param.rotation = part.rotation;
//           }
//           if (part.seekId) {
//             param.model_code = part.seekId.toString();
//           }
//           mySqlutil.execute(projectContentDao.insert(param)).then(() => {
//             callback();
//           }).catch((err2) => {
//             rej(err2);
//           });
//         } else {
//           callback();
//         }
//       }, ((err1) => {
//         if (err1) rej(err1);
//       }));
//     }).catch((err) => {
//       rej(err);
//     });
//   }
// });

/**
 * 根据输入方案（户型）数据，构建方案（户型）实体对象
 * @param designMap
 * @param userId
 * @returns {{}}
 */
const createDesign = (designMap) => {
  const design = {};
  if (designMap) {
    // 用户信息
    if (designMap.userId) {
      design.user_id = designMap.userId;
    }
    if (designMap.login) {
      design.user_login = designMap.login;
    }
    if (designMap.vendorCode) {
      design.vendor_code = designMap.vendorCode;
    }
    if (designMap.agencyId) {
      design.agency_id = designMap.agencyId;
    }
    // 户型编码
    if (designMap.designId) {
      design.designId = designMap.designId;
    } else {
      design.designId = uuid4();
    }
    if (designMap.sourceId) {
      design.source_designId = designMap.sourceId;
    }
    // 方案类型  2 方案 3 样板间  4户型
    if (designMap.assetType) {
      design.asset_type = parseInt(designMap.assetType, 10);
    }
    // 户型背景底图
    if (designMap.backgroundImage) {
      design.background_image = designMap.backgroundImage;
    }
    if (designMap.area && !isNaN(parseFloat(designMap.area))) {
      design.area = designMap.area;
    }
    // 户型描述
    if (designMap.data) {
      if (designMap.data.totalarea) {
        // 户型背景底图
        design.total_area = parseFloat(designMap.data.totalarea).toFixed(2);
        if (!design.area) {
          design.area = design.total_area;
        }
      }
    }

    // 取出户型数据，如户型所属省市区、小区，以及户型大小等
    // 户型名称
    if (designMap.name) {
      design.name = designMap.name;
    }
    if (designMap.space) {
      design.space = designMap.space;
    }
    if (designMap.bedrooms) {
      design.bedrooms = designMap.bedrooms;
    }
    if (designMap.livingRooms) {
      design.living_rooms = designMap.livingRooms;
    }
    if (designMap.restrooms) {
      design.restrooms = designMap.restrooms;
    }

    if (designMap.realArea && !isNaN(parseFloat(designMap.realArea))) {
      design.real_area = designMap.realArea;
    }
    if (designMap.style) {
      design.style = designMap.style;
    }
    if (designMap.description) {
      design.description = designMap.description;
    }
    if (designMap.province) {
      if (designMap.province.text) {
        design.province = designMap.province.text;
      }
      if (designMap.province.code) {
        design.province_code = designMap.province.code;
      }
    }
    // design.province = '浙江省';
    // design.province_code = '330000000';
    if (designMap.city) {
      if (designMap.city.text) {
        design.city = designMap.city.text;
      }
      if (designMap.city.code) {
        design.city_code = designMap.city.code;
      }
    }
    // design.city = '杭州市';
    // design.city_code = '330100000';
    if (designMap.district) {
      if (designMap.district.text) {
        design.district = designMap.district.text;
      }
      if (designMap.district.code) {
        design.district_code = designMap.district.code;
      }
    }
    if (designMap.neighbor) {
      design.neighbor = designMap.neighbor;
    }

    if (designMap.sharedBrand) {
      design.shared_brand = designMap.sharedBrand;
    }

    if (designMap.gmtCreate) {
      design.gmt_Create = designMap.gmtCreate;
    }
  }
  return design;
};
/**
 * 执行方案（户型）保存操作
 * @param designMap
 * @param userId
 */
const exectSaveDesign = (designMap) => {
  // 构建方案（户型）对象
  const design = createDesign(designMap);

  let strImage;
  let strTopImage;
  let strData;
  let imageName;
  let top3DImageName;
  if (designMap) {
    // 获取方案截图二进制流
    if (designMap.data && designMap.data.thumbnail3d) {
      // 取出户型或方案截图，下一步需要保存到mongodb中
      strImage = designMap.data.thumbnail3d;
    }
    if (designMap.data && designMap.data.thumbnail3dTop) {
      // 取出户型或方案顶视图，下一步需要保存到mongodb中
      strTopImage = designMap.data.thumbnail3dTop;
    }
    if (designMap.data && designMap.data.thumbnail3dTopCam) {
      // 取出户型或方案辅助数据，下一步需要保存到Mysql，方案基本信息表
      design.thumbnail3d_top_cam = designMap.data.thumbnail3dTopCam;
    }
    if (designMap.data && designMap.data.imageName) {
      // 取出户型或方案截图，下一步需要保存到mongodb中
      imageName = designMap.data.imageName;
    }
    if (designMap.data && designMap.data.top3DImageName) {
      // 取出户型或方案截图，下一步需要保存到mongodb中
      top3DImageName = designMap.data.top3DImageName;
    }

    // 取出户型方案的Json数据
    strData = designMap.data.data;
  }
  // 保存方案户型json数据
  // 保存方案三维场景截图到mongodb
  // 保存方案中所适用的模型
  // 删除原有设计方案主体数据
  return Promise.all([projectJsonCrtl.saveDesignJson(strData, design.designId, design.user_id),
    // saveStrImage(strImage, `${design.designId}_jt.jpg`), saveStrImage(strTopImage, `${design.designId}_top3D.jpg`),
    // copyAndSaveImage(imageName, `${design.designId}_jt.jpg`), copyAndSaveImage(top3DImageName, `${design.designId}_top3D.jpg`),
    // saveContentByProject(strData, design.designId),
    mySqlutil.execute(squel.delete().from('project').where('designId = ?', design.designId).toString())
  ]).then(() => {
    const sql = squel.insert().into('project').setFields(design).toString();
    mySqlutil.execute(sql).then(() => {

    }).catch((err) => {
      logUtil.info('design is');
      logUtil.info(`source_designId:${design.source_designId}`);
      logUtil.info(err);
    });
  }).then(() => design);
};

/**
 * 解析json文件
 * 将户型JSON数据转换为对应的户型对象结构
 */
const analysisJsonFile = (filePath, filename) => {
  // 同步读JSON文件
  const fileData = fs.readFileSync(filePath, 'utf-8');

  const info = JSON.parse(fileData);
  // "free":"[{"area":77.83610882629577,"realArea":77.83610882629577,
  // "obsCommId":"3FO4K4T3T4TO","obsUserId":"3FO4K41XJEXM",
  // "cadImported":false,"name":"美加湖滨新城-副本"}]"
  let free = info.free;
  if (typeof free === 'string') {    free = JSON.parse(free);  }
  if (free && free.length > 0) {    free = free[0];  }
  if (typeof free === 'string') {    free = JSON.parse(free);  }
  if (free && free.length > 0) {      free = free[0];    }
  if (typeof free === 'string') {    free = JSON.parse(info.free[0]);  }

  const homeInfo = {};
  var filename = filename.substr(0,filename.length-5);

  var names=filename.split(']');
  if(names.length==6){ //酷家乐 户型
    homeInfo.province = { code: names[1].substr(1), text: names[0].substr(1) };
    homeInfo.city = { code: names[3].substr(1), text: names[2].substr(1)};
    homeInfo.neighbor = names[4].substr(1);
    homeInfo.name =names[4].substr(1);
    homeInfo.designId = names[5];
  }
  else{//设计家户型
    homeInfo.designId = filename.split(".")[0];
    if (info.name) {
      const names = info.name.split(' ');
      if (names && names.length > 1) {
        homeInfo.name = names[1].concat((names.length > 2) ? names[2] : '');
      } else {
        homeInfo.name = info.name;
      }
    }
    if (!homeInfo.name) {
      homeInfo.name = free.name;
    }
  }



  // homeInfo.name = `${homeInfo.designId}_1220`;

  homeInfo.description = new Date().toDateString();

  homeInfo.data = { data: info.data.data, totalarea: (free.area ? free.area.toFixed(2) : null) };
  homeInfo.userLogin = 'jmyd';
  homeInfo.vendorCode = '111';
  homeInfo.assetType = 4;
  homeInfo.userId = 1;
  if (free.area) {
    homeInfo.area = free.area.toFixed(2);
  }
  if (free.area) {
    homeInfo.realArea = free.area.toFixed(2);
  }
  if (free.bedroomNum) {
    homeInfo.bedrooms = free.bedroomNum;
  }
  if (free.livingroomNum) {
    homeInfo.livingRooms = free.livingroomNum;
  }
  if (free.bathroomNum) {
    homeInfo.restrooms = free.bathroomNum;
  }
  if (free.province) {
    homeInfo.province = { code: `${free.province.id}000`, text: free.province.name };
  }
  if (free.city) {
    homeInfo.city = { code: `${free.city.id}000`, text: free.city.name };
  }
  if (free.district) {
    homeInfo.district = { code: `${free.district.id}000`, text: free.district.name };
  }
  if (free.style) {
    homeInfo.style = free.style.name;
  }
  if (free.neighbor) {
    homeInfo.neighbor = free.neighbor;
  }
  // if (!homeInfo.province) {
  //   homeInfo.province = { code: '330000000', text: '浙江省' };
  // }
  // if (!homeInfo.city) {
  //   homeInfo.city = { code: '330100000', text: '杭州市' };
  // }
  return homeInfo;
};

/**
 * 递归遍历文件夹，取出JSON文件解析
 * @param filePath
 * @returns {*}
 */
const ergodicFolderJson = (dataPath, analysisJson) => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      rej(err);
    }
    // 异步，一次执行10个
    eachLimit(files, 5, (filename, callback) => {
      const filePath = path.join(dataPath, filename);
      fs.stat(filePath, (err1, stats) => {
        if (err1) {
          logUtil.error(err1);
          // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
        try {
          if (stats && stats.isFile()) { // 是文件
            if (path.extname(filePath) === '.json') {
              // 分析JSON文件
              const homeInfo = analysisJson(filePath, filename);
              if (!homeInfo.designId) {
                homeInfo.designId = uuid4();
              }
              exectSaveDesign(homeInfo)
                .then((result) => {
                  fs.unlink(filePath, (err) => {
                    if (err) logUtil.error(err);
                    logUtil.info(homeInfo.name);
                    setImmediate(callback);
                  });
                })
                .catch((err) => {
                  logUtil.error(err);
                  setImmediate(callback);
                });
            } else {
              // 如果为非Json文件，则给出错误信息
              logUtil.info(`not json:${filePath}`);
              setImmediate(callback);
            }
          } else {
            // 如果是文件夹，则递归调用本函数
            ergodicFolderJson(filePath, analyzeJson);
            setImmediate(callback);
          }
        } catch (err2) {
          logUtil.error(err2);
          // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
      });
    }, ((err1) => {
      if (err1) {
        console.log(err1);
        rej(err1);
      } else {
        res();
      }
    }));
  });
});


/**
 * 递归变量文件夹下所有jpg图片文件
 * @param dataPath
 * @param callbackOperate
 */
const ergodicFolderImage = (dataPath) => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      rej(err);
    }
    // 异步，一次执行10个
    eachLimit(files, 10, (filename, callback) => {
      const filePath = path.join(dataPath, filename);
      fs.stat(filePath, (err1, stats) => {
        if (err1) {
          // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
        try {
          if (stats && stats.isFile()) { // 是文件
            if (path.extname(filePath) === '.jpg') {
              gridFSBuckets.save(filePath,filename,"project_image",true).then(()=>{
                setImmediate(callback);
              }).catch((err)=>{
                logUtil.error(err);
                setImmediate(callback);
              })
              // // 读取二进制文件
              // const imageData = fs.readFileSync(filePath, 'base64');
              // callbackOperate(imageData, filename)
              //   .then((result) => {
              //     // fs.unlink(filePath, (err) => {
              //     //   if (err) logUtil.error(err);
              //     //   logUtil.info(filename);
              //     //   setImmediate(callback);
              //     // });
              //     logUtil.info(filename);
              //     setImmediate(callback);
              //   })
              //   .catch((err) => {
              //     logUtil.error(err);
              //     setImmediate(callback);
              //   });
            } else {
              // 如果为非Json文件，则给出错误信息
              logUtil.info(`not json:${filePath}`);
              setImmediate(callback);
            }
          } else {
            // 如果是文件夹，则递归调用本函数
            ergodicFolderImage(filePath);
            setImmediate(callback);
          }
        } catch (err2) {
          // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
      });
    }, ((err1) => {
      if (err1) {
        console.log(err1);
        rej(err1);
      } else {
        res();
      }
    }));
  });
});

/**
 * 批量导入酷家乐、计家户型数据 2017-12-20
 * @param ctx
 * @returns {Promise.<void>}
 */
exports.batchImportDesignHomeData = (dataPath) => {
  try {
    ergodicFolderJson(dataPath, analysisJsonFile);
    // ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

/**
 * 批量导入户型图片
 * @param dataPath
 */
exports.batchImportDesignHomeImage = (dataPath) => {
  try {
    ergodicFolderImage(dataPath);
    // ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

